const express = require('express');
const bodyParser = require('body-parser');
const fs = require('fs');
const { json } = require('body-parser');

const app = express();

app.use(express.static('www'));
app.use(bodyParser.urlencoded({ extended: false }));


app.listen(3000, () => { console.log('http://localhost:3000') });

app.post('/zhuce', (req, res) => {
    console.log(req.body);
    var data = fs.readFileSync('./users.txt');
    if (data.toString()) {
        var arr = data.toString().split('$');
        var arr1 = arr.map((item) => JSON.parse(item));

        var isShow = true;
        for (var i = 0; i < arr1.length; i++) {
            if (req.body.username == arr[i].username) {
                isShow = false;
            }
        }

        if (isShow) {
            //没有当前这个用户
            var str = '$' + JSON.stringify(req.body);
            fs.appendFile('./users.txt', str, function (err) {
                if (!err) {
                    res.json({ success: 1, data: '添加成功' })
                }
            })

        } else {
            res.json({ success: 0, data: '当前用户已存在' })
        }

    } else {
        var str = JSON.stringify(req.body);
        fs.appendFile('./users.txt', str, function (err) {
            if (!err) {
                res.json({ success: 1, data: "添加成功" });
            }
            
        })
    }
})